#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "bool.h"
#include "data.h"
#include "key.h"
#include "dict.h"
#include "abb.h"

struct sdict {
	Abb arbol;
};

dict dict_empty (void){
	dict dic = (dict)calloc(1,sizeof(struct sdict));
	dic->arbol = abb_empty();
	return dic;
}

void dict_add (dict dic, Word w, Def f) {
	data definicion = data_fromString(f);
	key palabra = key_fromString(w);
	abb_add(dic->arbol,palabra,definicion);
	definicion = data_destroy(definicion);
	palabra = key_destroy(palabra);
}

bool dict_exists (dict d, Word w) {
	key palabra;
	bool r;
	palabra = key_fromString(w);
	r = abb_exists(d->arbol,palabra);
	palabra = key_destroy(palabra);

	return r;
}

Def dict_search (dict d, Word w) {
	if (dict_exists(d,w)){
		key palabra = key_fromString(w);
		data q = abb_search(d->arbol,palabra);
		palabra = key_destroy(palabra);

		return data_toString(q);
	}
	else{
		return NULL;
	}
}

void dict_del (dict d, Word w) {
	key palabra = key_fromString(w);
	abb_del(d->arbol,palabra);
	palabra = key_destroy(palabra);
}

void dict_pprint (dict d) {
	abb_pprint(d->arbol);
}

int dict_length (dict d) {
	return (abb_length(d->arbol));
}

dict dict_destroy (dict d) {
	if(d != NULL && d->arbol != NULL) {
		d->arbol = abb_destroy(d->arbol);
		free(d);
		d = NULL;
	}
	else{
		free(d);
		d = NULL;
	}
	return d;
}

int word_maxLen (void) {
	return (key_maxLen());
}

dict dict_fromFile(char *nomfile) {
	dict d = (dict)calloc(1,sizeof(struct sdict));
	d->arbol = abb_fromFile(nomfile);
	return d;
}

void dict_toFile(char *nomfile, dict d){
	 abb_toFile(nomfile,d->arbol);
}

